from rest_framework import serializers
import re
from datetime import datetime, timedelta
from django.contrib.auth import get_user_model
from rest_framework.validators import UniqueValidator
from users.models import UserProfile

from .models import VerifyCode
User = get_user_model()
# 11位手机号码正则表达式
TEL_REGEXP = '^(13\d|14[5|7]|15\d|166|17[3|6|7]|18\d)\d{8}$'


class SmsSerializer(serializers.Serializer):

    mobile = serializers.CharField(max_length=11, help_text='注册手机号')

    def validate_mobile(self, mobile):
        """
        验证手机号码
        :param mobile:
        :return:
        """
        one_min_ago = datetime.now() - timedelta(hours=0, minutes=1, seconds=0)
        if User.objects.filter(mobile=mobile).exists():
            raise serializers.ValidationError("用户已存在")
        elif not re.match(TEL_REGEXP, mobile):
            raise serializers.ValidationError("手机号码非法")
        if VerifyCode.objects.filter(mobile=mobile, add_time__gt=one_min_ago).exists():
            raise serializers.ValidationError("操作过于频繁，请稍后再试")
        return mobile

    def update(self, instance, validated_data):
        pass

    def create(self, validated_data):
        pass


class UserRegSerializer(serializers.ModelSerializer):
    code = serializers.CharField(required=True, write_only=True, min_length=4, max_length=4, error_messages={
        "blank": "请输入验证码",
        "max_length": "验证码格式错误",
        "min_length": "验证码格式错误",
    }, help_text='手机验证码')
    username = serializers.CharField(required=True, allow_blank=False,help_text='用户名',
                                     validators=[UniqueValidator(queryset=User.objects.all(), message="用户已存在")])
    password = serializers.CharField(help_text='密码', style={'input_type': 'password'}, write_only=True)

    def validate_code(self, code):
        verify_records = VerifyCode.objects.filter(mobile=self.initial_data['username']).order_by('-add_time').first()
        # print(verify_records)
        if verify_records:
            five_code_ago = datetime.now() - timedelta(hours=0, minutes=5, seconds=0)
            if five_code_ago > verify_records.add_time or verify_records.code != code:
                raise serializers.ValidationError("无效验证码")
        else:
            raise serializers.ValidationError("验证码错误")

    def validate(self, attrs):
        attrs['mobile'] = attrs['username']
        del attrs['code']
        return attrs

    def create(self, validated_data):
        user = super().create(validated_data=validated_data)
        user.set_password(validated_data['password'])
        user.save()
        return user

    class Meta:
        model = User
        fields = ('username', 'code', 'mobile', 'password')


class UserDetailSerializer(serializers.ModelSerializer):
    """
    用户详情序列化类
    """
    mobile = serializers.IntegerField(read_only=True, help_text='手机号')

    class Meta:
        model = User
        fields = ('name', 'gender', 'email', 'birthday', 'mobile')
